import instance from './intercept'

const headersDefault = {
  ContentType: 'application/json;charset=UTF-8'
}

const API_DOMAIN = import.meta.env.VITE_API_DOMAIN

const request = (
  { baseURL = API_DOMAIN, headers = headersDefault, method, url, data, params, responseType }: any,
  alterErr = true
): Promise<any> => {
  return new Promise((resolve, reject) => {
    Object.assign(headers, { Authorization: `Bearer ${window.$token}` })
    instance({ baseURL, headers, method, url, params, data, responseType })
      .then(async (resp: any) => {
        // status >= 200 && status < 300 满足这个条件都会进入then
        if (resp.status === 200) {
          // 正常返回
          if (!resp.data.skipResolve) {
            resolve({
              status: resp.status,
              statusText: resp.statusText,
              origin: resp.data,
              success: resp.data.success,
              message: resp.data?.message,
              data: resp.data?.data
            })
          }
        } else {
          // 错误返回
          const msg = resp.data?.message || url + ' 请求失败'
          errHandler(alterErr, resp.status, msg)
          reject({
            status: resp.status,
            statusText: resp.statusText,
            origin: resp.data,
            success: false,
            message: msg,
            data: resp.data?.data
          })
        }
      })
      .catch((err: any) => {
        const msg = err?.data?.message || err?.message || url + ' 请求失败'
        errHandler(alterErr, err.status, msg)
        reject({
          status: err.status,
          statusText: err?.data?.message || err?.message,
          origin: err?.data,
          success: false,
          message: msg,
          data: err?.data?.data
        })
      })
  })
}

const errHandler = (alterErr: boolean, status: number, msg: string) => {
  if (alterErr) {
    if (status === 401) {
      // 认证失败, 重新登录
      // confirm(`${msg}, 是否重新登录`, () => {
      //   const router = useRouter()
      //   router.push({ name: 'Logout' })
      // })
      console.error('认证失败')
    } else {
      // ElMessage.error(msg)
      console.error(msg)
    }
  }
}

const post = (
  { baseURL, headers, url, data, params, responseType }: any,
  alterErr = true
): Promise<any> => {
  return request({ baseURL, headers, method: 'post', url, data, params, responseType }, alterErr)
}

const get = (
  { baseURL, headers, url, data, params, responseType }: any,
  alterErr = true
): Promise<any> => {
  return request({ baseURL, headers, method: 'get', url, data, params, responseType }, alterErr)
}

export { get, post }
